package com.rose.lvye.spandemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;


public class MainActivity extends ActionBarActivity implements OnClickListener {
    private GridView spanGdv;
    private EditText inputEdt;
    private ImageButton spanBtn;
    private SpanGridViewAdapter adapter;
    private int[] data = new int[]{
            R.drawable.d01,
            R.drawable.d02,
            R.drawable.d03,
            R.drawable.d04,
            R.drawable.d05,
            R.drawable.d06,
            R.drawable.d07,
            R.drawable.d08,
            R.drawable.d09,
            R.drawable.d10,
            R.drawable.d11,
            R.drawable.d12,
            R.drawable.d13,
            R.drawable.d14,
            R.drawable.d15,
            R.drawable.d16,
            R.drawable.d17,
            R.drawable.d18,
            R.drawable.d19,
            R.drawable.d20
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inputEdt = (EditText) findViewById(R.id.editText);
        spanBtn = (ImageButton) findViewById(R.id.button);
        spanBtn.setOnClickListener(this);
        spanGdv = (GridView) findViewById(R.id.gridView);
        adapter = new SpanGridViewAdapter(this, data);
        spanGdv.setAdapter(adapter);
        spanGdv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getSpan(data[position]);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (spanGdv.getVisibility() == View.GONE) {
            spanGdv.setVisibility(View.VISIBLE);
        } else {
            spanGdv.setVisibility(View.GONE);
        }
    }

    private void getSpan(int resourceId){
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
        //  根据Bitmap对象创建ImageSpan对象
        ImageSpan imageSpan = new ImageSpan(this, bitmap);
        //  创建一个SpannableString对象，以便插入用ImageSpan对象封装的图像
        SpannableString spannableString = new SpannableString("face");
        //  用ImageSpan对象替换face
        spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //  将随机获得的图像追加到EditText控件的最后
        inputEdt.append(spannableString);
    }


}
